import React from "react"
import {Link} from "react-router-dom"
import {Menu} from "antd";
import {keySeparator, rootPath} from "../../../../shared/init"

const SubMenu = Menu.SubMenu
const MenuItem = Menu.Item

const permissionMenu = (menus, resources) => {
	const antMenus = menus.map(m => {
			//无子菜单
			if (!m.children || m.children.length === 0) {
				if (m.component === undefined) {
					return null;
				} else {
					return resources.some(r => r === m.code || m.code === 'profile') ? m : null
				}
			}
			m.children = permissionMenu(m.children, resources)
			return m.children && m.children.length > 0 ? m : null
		}
	).filter(m => !!m)
	return antMenus
}


const itemIcon = (item) => {
	if (item.image) {
		return <img alt={''} src={item.image} className={'zr-menu-item-image'}/>
	}
	if (item.icon) {
		return item.icon
	}
	if (item['iconClass']) {
		return <i className={`zr-menu-icon iconfont ${item['iconClass']}`}/>
	}
	return undefined
}

/**
 * 根据菜单数据生成菜单
 * @param menus
 * @param pKey
 * @param pRoute
 * */
const createMenus = (menus, pKey, pRoute) => {
	return menus.map(item => {
		const _key = pKey ? `${pKey}${keySeparator}${item.key}` : `${item.key}`
		const _route = `${pRoute}/${item.key}`

		const _label = (
			<span className="menu-item">
        {itemIcon(item)}
				<span>{item.label}</span>
      </span>
		)

		return item.children
			? createSubMenu(item.children, _key, _route, _label)
			: createMenuItem(_label, _key, _route, item.param, item.search)
	})
}


/**
 * 生成子菜单
 * @param items
 * @param key
 * @param route
 * @param label
 * */
const createSubMenu = (items, key, route, label) => {
	return (
		<SubMenu title={label} key={`${rootPath}${keySeparator}${key}`}>
			{createMenus(items, key, route)}
		</SubMenu>
	)
}


/**
 * 生成菜单项
 * @param key
 * @param route
 * @param label
 * */
const createMenuItem = (label, key, route, param, search) => {
	const searchConnector = search ? '?' : ''
	const _search = search ? Object.entries(search).map(([k, v]) => `${k}=${v}`).join('&') : ""
	const _searchStr = `${searchConnector}${_search}`
	const _mKey = param
		? `${rootPath}${keySeparator}${key}${keySeparator}${param.value}`
		: `${rootPath}${keySeparator}${key}${_searchStr}`

	return (
		<MenuItem key={_mKey}>
			{param
				? <Link to={`/${route}/${param.value}${_searchStr}`}>{label}</Link>
				: <Link to={`/${route}${_searchStr}`}>{label}</Link>
			}
		</MenuItem>
	)
}

const menuSettings = {
	theme: "dark",
	style: {width: "100%"},
	mode: "inline",
	inlineCollapsed: true,
	inlineIndent: 20
}

export {
	createMenus,
	menuSettings,
	keySeparator,
	permissionMenu
}